package 力扣._617_合并二叉树;

import 力扣.公用数据结构.TreeNode;

public class Solution {
    void merge(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null)
            return;
        if (root1 != null && root2 != null) {
            root1.val += root2.val;
            //左右子树
            if (root1.left == null && root2.left != null) {
                root1.left = root2.left;
                root2.left = null;
            }
            if (root1.right == null && root2.right != null) {
                root1.right = root2.right;
                root2.right = null;
            }

        }
        if (root2 != null) {
            merge(root1.left, root2.left);
            merge(root1.right, root2.right);
        } else {
            merge(root1.left, null);
            merge(root1.right, null);
        }

    }

    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) {
            root1 = root2;
            root2 = null;
        }
        merge(root1, root2);
        return root1;

    }
}
